package heartbeat;
import java.util.List;
import java.util.concurrent.Executor;

import sdm.repackaged.org.json.JSONException;
import sdm.repackaged.org.json.JSONObject;

public class Main 
{
	protected static List<String> mChannelNames;
	
	public static void main(String[] args) throws Exception
	{
		final Heartbeat hb = new Heartbeat();
		final TcpClient pClient1 = hb.addClient("sdm-jschmitz.wv.mentorg.com", 9004, false);
		PCallback<MessageCBType> simpleEchoCallback = new PCallback<MessageCBType>()
		{
			@Override
			public void invoke(MessageCBType result) 
			{
				Packet pPacket = result.packet();
				System.out.println(pPacket.message());
			}
		};
		
		PCallback<ChannelsCBType> channelsReceivedCallback = new PCallback<ChannelsCBType>()
		{
			@Override
			protected void invoke(ChannelsCBType result)
			{
				TcpClient pReceiver = result.client();
				mChannelNames = result.channels();
				
				//Send authentication to the PM heartbeat server.
				try
				{
					hb.sendAuthentication(pReceiver, new JSONObject().put("encodedConnectionId", "4bZPNucQ4Zp8AQlpTePwPDiPXXR5CjlEc9zALEnJ72fxnL02STmPRBmrg4le0KjrV53fpzXsxruVTObGS5k8VQ%3D%3D"));
				}
				catch(JSONException e) {}
			}
			
		};
		
		PCallback<MessageCBType> authenticatedCallback = new PCallback<MessageCBType>()
		{
			@Override
			protected void invoke(MessageCBType result) 
			{
				
				System.out.println("Authenticated!");
				final TcpClient pReceiver = result.client();
				
				//Subscribe to each channel.
				hb.subscribeTo(pClient1, mChannelNames);
				
				hb.write(pReceiver, new Packet(8, result.packet().message()));
			}
					
		};
		
		PCallback<TcpClient> clientDisconnectCallback = new PCallback<TcpClient>()
		{

			@Override
			protected void invoke(TcpClient pClient) 
			{
				System.out.println("Client Disconnect");
				System.out.println(pClient);
			}
		};
			
		
		hb.setOnClientDisconnectCallback(pClient1, clientDisconnectCallback);
		hb.setOnMessageCallback(pClient1, simpleEchoCallback);
		hb.setOnChannelsReceivedCallback(pClient1, channelsReceivedCallback);
		hb.setOnAuthenticationCallback(pClient1, authenticatedCallback);
		Executor ex = new ThreadPerTaskExecutor();
		ex.execute(hb);
		
	}
}
